// ignore_for_file: unnecessary_overrides, avoid_print, prefer_typing_uninitialized_variables, avoid_init_to_null

import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:path/path.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/app_permission/yt_tab_view_model.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/time_range_picker.dart';
import 'package:yt_devops/components/yt_bottom_picker.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/alarm/alarm_detail/alarm_detail_binding.dart';
import 'package:yt_devops/pages/alarm/alarm_detail/alarm_detail_controller.dart';
import 'package:yt_devops/pages/alarm/alarm_detail/alarm_detail_view.dart';
import 'package:yt_devops/pages/alarm/alarm_home/alarm_home_model.dart';
import 'package:yt_devops/pages/alarm/alarm_home/alarm_list/alarm_list_model.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_site_tags.dart';
import 'package:yt_devops/pages/devices/device_list/components/filter_status_tags.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/alarm/alarm_services.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/alarm_util.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/navigate_utils.dart';

class AlarmHomeController extends GetxController
    with GetTickerProviderStateMixin {
  final AlarmHomeState state = AlarmHomeState();
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  AlarmListRequestParams reqParams = AlarmListRequestParams();
  List<AlarmModel>? alarmsList = [];
  AlarmServices alarmServices = AlarmServices();
  AlarmNumState alarmNumState = AlarmNumState();
  String noDataText = "";
  StreamSubscription? changeLanguageSubscrip;

  /// 搜索
  FocusNode searchSiteFocusNode = FocusNode();
  TextEditingController textController = TextEditingController();
  BrnSearchTextController searchController = BrnSearchTextController();

  String pageName = ResKey.alarm.tr;
  num deviceId = -1;
  var siteId = null;
  late int role;
  dynamic arguments;

  /// 筛选
  bool isLoad = false;
  String startTime = '';
  String endTime = '';
  List<AlarmStatusGradeType> selectTags = [];
  List<dynamic> selectTag = [];
  List<dynamic> selectHistoryTag = [];

  ///是否是历史告警
  List<String> tabs = [ResKey.currentAlarm.tr, ResKey.historyAlarm.tr];
  bool? isTabPage = false; //是否是tab页面 是的话没有返回 显示中间tab
  TabController? tabController;

  /// 已选中的站点列表
  List<SiteTagModel> selectedSites = [];
  bool isFirstLoad = true;

  late List<String> tabPermissions;

  List<YtTabViewModel> filterPermission = [];
  bool get isHistoryAlarm =>
      FuncUtils.isListEmpty(filterPermission) || tabController == null
          ? false
          : filterPermission[tabController!.index].permissionString ==
              tabPermissions[1];
  @override
  void onInit() {
    super.onInit();
    changeLanguageSubscrip =
        EventBusUtil.getInstance().on<SwitchLanguage>().listen((event) {
      Log.d('SwitchLanguage===');
      initData();
    });
  }

  void getTabPermission(AlarmPageType? alarmPageType) {
    switch (alarmPageType) {
      case AlarmPageType.all:
        tabPermissions = [
          PermissionConstant.operationAlarmCurrentAlarm,
          PermissionConstant.operationAlarmHistoryAlarm
        ];

      case AlarmPageType.site:
        tabPermissions = [
          PermissionConstant.homeSiteManageAlarmCurrentAlarm,
          PermissionConstant.homeSiteManageAlarmHistoryAlarm
        ];

      default:
        tabPermissions = [
          PermissionConstant.deviceDetailAlarmCurrentAlarm,
          PermissionConstant.deviceDetailAlarmHistoryAlarm
        ];
    }
  }

  initData() {
    tabController = TabController(length: tabs.length, vsync: this);
    refreshController = RefreshController(initialRefresh: false);
    // tabController!.addListener(() {
    //   if (tabController!.index == tabController!.animation!.value) {
    //     isHistoryAlarm = tabController!.index;
    //     _clearChoose();
    //     onRefresh();
    //   }
    // });
    readCacheRole();
    judgeAlarmFromWhere();
    initAlarmHome();
  }

  /// 初始化告警列表
  void initAlarmHome() {
    getAlarmsNum();
    loadList();
  }

  /// 读取缓存角色
  void readCacheRole() {
    if (UserEntityManager().load().roles != null) {
      var roles = UserEntityManager().load().roles;
      role = roles![0].roleId!;
    }
  }

  /// 判断告警模块类型
  void judgeAlarmFromWhere() {
    if (AlarmUtil.fromModule == AlarmFromWhereType.device.value) {
      _getDeviceModuleParams();
    } else if (AlarmUtil.fromModule == AlarmFromWhereType.currentSite.value) {
      _getCurrentSiteParams();
    }

    collectAlarmNumResParams();
    _collectListResPalarms();
  }

  /// 获取设备模块参数 - 设备告警调用
  void _getDeviceModuleParams() {
    try {
      // pageName = Get.arguments['deviceName'];
      // deviceId = Get.arguments['deviceId'];
      reqParams.deviceId = deviceId;
    } catch (e) {
      print(e);
    }
  }

  /// 获得单站点模块参数 - 站点告警调用
  void _getCurrentSiteParams() {
    try {
      // pageName = Get.arguments['siteName'] + ResKey.alarm.tr;
      // siteId = Get.arguments['siteId'];
      reqParams.siteIds = [];
      reqParams.siteIds!.add(siteId);
    } catch (e) {
      print(e);
    }
  }

  /// 获取搜索列表站点名称
  void getSearchSiteName(String? alarmName) {
    reqParams.alarmName = alarmName;

    getAlarmsNum();
    loadList();
  }

  /// 收集告警数量请求参数
  dynamic collectAlarmNumResParams() {
    Log.d('AlarmUtil==' + AlarmUtil.fromModule.toString());
    Map<String, dynamic> param = {
      'isHistoryAlarm': isHistoryAlarm ? 1 : 0,
      'deviceName': reqParams.alarmName
    };
    if (reqParams.alarmName != null) {
      param['deviceName'] = reqParams.alarmName;
    }
    if (isHistoryAlarm) {
      param['recoverType'] = reqParams.recoverType;
    } else {
      param['status'] = reqParams.status;
    }
    if (reqParams.startTime != null && reqParams.startTime!.isNotEmpty) {
      param['startTime'] = reqParams.startTime!.trim();
    }
    if (reqParams.endTime != null && reqParams.endTime!.isNotEmpty) {
      param['endTime'] = reqParams.endTime!.trim();
    }

    if (AlarmUtil.fromModule == AlarmFromWhereType.allSites.value) {
      /// 所有站点告警模块
      return param;
    } else if (AlarmUtil.fromModule == AlarmFromWhereType.currentSite.value) {
      param['siteId'] = siteId;

      /// 当前站点告警模块
      return param;
    } else {
      /// 当前设备告警模块
      param['deviceId'] = deviceId;

      /// 当前站点告警模块
      return param;
    }
  }

  /// 获取告警数量
  Future getAlarmsNum() async {
    var params = collectAlarmNumResParams();
    await alarmServices.getDiffAlarmNumNew(params).then((value) {
      alarmNumState = AlarmNumState.fromMap(value);
      _computeAlarmSum();
      update();
    }, onError: (err) {
      // dismissLoading();
      handleException(err);
      return false;
    });
  }

  /// 计算告警总数
  void _computeAlarmSum() {
    state.alarmNum = alarmNumState.alarmNum;
    state.errorNum = alarmNumState.errorNum;
    state.warnNum = alarmNumState.warnNum;
    state.infoNum = alarmNumState.infoNum;
    state.alarmSum =
        state.alarmNum! + state.errorNum! + state.warnNum! + state.infoNum!;
    update();
  }

  /// 收集告警列表请求参数
  Object _collectListResPalarms() {
    Map<String, dynamic> baseMap = {
      "deviceName": reqParams.alarmName!.trim(),
      "startTime": reqParams.startTime!.trim(),
      "endTime": reqParams.endTime!.trim(),
      "levels": reqParams.levels ?? [],
      "isConfirm": reqParams.isConfirm,
      "current": reqParams.current,
      "pageSize": reqParams.pageSize,
      'isHistoryAlarm': isHistoryAlarm ? 1 : 0
    };
    if (isHistoryAlarm) {
      baseMap['recoverType'] = reqParams.recoverType;
    } else {
      baseMap['status'] = reqParams.status;
    }

    if (AlarmUtil.fromModule == AlarmFromWhereType.allSites.value) {
      /// 所有站点告警模块
      baseMap["siteIds"] = [];
      return baseMap;
    } else if (AlarmUtil.fromModule == AlarmFromWhereType.currentSite.value) {
      /// 当前站点告警模块
      baseMap["siteIds"] = reqParams.siteIds;
      return baseMap;
    } else {
      /// 当前设备告警模块
      baseMap["deviceId"] = reqParams.deviceId;
      return baseMap;
    }
  }

  /// 请求告警列表参数
  Future<void> loadList() async {
    var params = _collectListResPalarms();
    // if (isFirstLoad) showLoading(toast: ResKey.loading.tr);
    Log.d('alarmServices===' + params.toString());
    var data = await alarmServices.getAlarmsListNew(params, onError: (error) {
      // dismissLoading();
      isFirstLoad = false;
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      dismissLoading();
      showError(error.message.toString());
      return false;
    });
    // dismissLoading();
    isFirstLoad = false;
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    if (data != null) {
      if (reqParams.current == 1) {
        alarmsList?.clear();
        // alarmsList?.add(AlarmModel(name: 'AlarmChartWidget'));
      }
      if (data['list'] != null) {
        var temp = List.of(data['list'])
            .map((item) => AlarmModel.fromJson(item))
            .toList();
        alarmsList?.addAll(temp);
      } else {
        alarmsList?.addAll([]);
      }
      if (data['total'] != null && data['total'] <= alarmsList?.length) {
        refreshController.loadNoData();
      }
      update();
    }
    dismissLoading();
  }
  // /// 请求告警列表参数
  // Future<void> loadList1(
  //     {RefereshType refereshType = RefereshType.refresh}) async {
  //   var params = _collectListResPalarms();
  //   try {
  //     if (refereshType == RefereshType.refresh ||
  //         refereshType == RefereshType.load) {
  //       var data = await alarmServices.getAlarmsListNew(params);
  //
  //       var temp = List.of(data['list'])
  //           .map((item) => AlarmModel.fromJson(item))
  //           .toList();
  //
  //       if (refereshType == RefereshType.refresh) {
  //         alarmsList = temp;
  //       } else {
  //         alarmsList!.addAll(temp);
  //       }
  //
  //       update();
  //       endRefresh(temp);
  //     } else {
  //       Configs.httpClient.requestWithLoading(() async {
  //         var data = await alarmServices.getAlarmsListNew(params);
  //         var temp = List.of(data['list'])
  //             .map((item) => AlarmModel.fromJson(item))
  //             .toList();
  //         if (refereshType == RefereshType.refresh ||
  //             refereshType == RefereshType.initial) {
  //           alarmsList = temp;
  //         } else {
  //           alarmsList!.addAll(temp);
  //         }
  //
  //         endRefresh(temp);
  //         update();
  //       }, onError: (err) {
  //         dismissLoading();
  //         handleException(err);
  //         endRefresh(null);
  //         return true;
  //       });
  //     }
  //   } catch (e) {
  //     endRefresh(null);
  //     rethrow;
  //   }
  // }

  /// 下拉刷新
  void onRefresh() {
    showLoading(toast: ResKey.loading.tr);
    reqParams.current = 1;

    getAlarmsNum();
    loadList();
  }

  /// 刷新结束
  void endRefresh(List<AlarmModel>? list) {
    noDataText = "";

    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
      if ((list?.length ?? 0) >= reqParams.current) {
        refreshController.resetNoData();
      }
    } else {
      if (list == null) {
        refreshController.loadFailed();
      } else if ((list.isEmpty) || ((list.length) < reqParams.current)) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    }
  }

  /// 上拉加载
  void onLoad() {
    reqParams.current++;
    loadList();
  }

  /// 去告警详情页
  void goAlarmDetail(alarmItem) {
    Log.d('goAlarmDetail===' + alarmItem.id.toString());
    var id = alarmItem!.id.toString();
    // Get.lazyPut<AlarmDetailController>(() => AlarmDetailController(), tag: id);
    // Get.to(
    //     () => AlarmDetailPage(
    //           tagName: id,
    //         ),
    //     routeName: '${RouterPath.alarmDetail}/$id',
    //     binding: AlarmDetailBinding(tag: id),
    //     arguments: {
    //       'id': alarmItem!.id,
    //     })?.then((value) {
    //   if (value == true) {
    //     onInit();
    //   }
    // });
    NavigateUtils.toAlarmDetail(alarmItem!.id)?.then((value) {
      if (value == true) {
        onInit();
      }
    });
  }

  @override
  void onClose() {
    super.onClose();

    changeLanguageSubscrip?.cancel();
    textController.dispose();
    searchController.dispose();
    searchSiteFocusNode.dispose();
    // tabController?.dispose();
  }

  /// 重置
  resetFilter(void Function(void Function()) setState) {
    Log.d('resetFilter==');
    _clearChoose();
    setState(() {});
  }

  _clearChoose() {
    /// 参数层
    reqParams.levels?.clear();
    reqParams.startTime = "";
    reqParams.endTime = "";
    reqParams.status = null;
    reqParams.recoverType = null;
    selectTag = [];

    /// UI层
    selectTags.clear();
    selectTag.clear();
    startTime = "";
    endTime = "";
    selectedSites = [];
  }

  /// 过滤弹窗
  toFilter(BuildContext context) {
    ytBottomPicker(
      context,
      minHeight: isTabPage != null && isTabPage! && isHistoryAlarm ? 450 : 350,
      mainButtonOnTap: () {
        isLoad = false;
        onRefresh();
        Get.back();
      },
      resetTap: (setstate) {
        resetFilter(setstate);
      },
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) => Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              /// 告警时间
              Container(
                margin: const EdgeInsets.only(top: 16, bottom: 6),
                child: TimeRangePicker(
                  title: ResKey.alarmTime.tr,
                  padding: EdgeInsets.only(right: 16.w),
                  startPlaceholder: ResKey.startTime.tr,
                  endPlaceholder: ResKey.stopTime.tr,
                  startTime: startTime,
                  endTime: endTime,
                  onChange: (start, end) {
                    startTime = start;
                    endTime = end;
                    reqParams.startTime =
                        '${startTime.replaceAll('/', '-')} 00:00:00';
                    reqParams.endTime =
                        '${endTime.replaceAll('/', '-')} 23:59:59';
                  },
                ),
              ),

              /// 站点
              const SizedBox(height: 3),
              Visibility(
                  visible: isTabPage != null && isTabPage!,
                  child: FilterSiteTags(
                    selectedSites: selectedSites,
                    onChange: (sites) {
                      selectedSites = sites;
                      print("一直是 $selectedSites");
                    },
                  )),

              /// 清除状态
              Visibility(
                  visible: isHistoryAlarm,
                  child: FilterStatusTags<dynamic>(
                    isHistoryAlarm
                        ? AlarmClearStatusType.values
                        : AlarmStatusType.values,
                    labelName: (status) => status.label,
                    title: ResKey.clearState.tr,
                    isSingleSelect: true,
                    spacing: 11.w,
                    tagWidth: 104.w,
                    selectTags: selectTag,
                    onSelect: (status) {
                      selectTag = status ?? [];
                      reqParams.recoverType = status?[0].value;
                      reqParams.status = status?[0].value;
                    },
                  )),
            ],
          ),
        );
      },
    );
  }

  /// 过滤弹窗
  toHistoryFilter(BuildContext context) {
    ytBottomPicker(
      context,
      minHeight: isTabPage != null && isTabPage! ? 450 : 350,
      mainButtonOnTap: () {
        isLoad = false;
        onRefresh();
        Get.back();
      },
      resetTap: (setstate) {
        resetFilter(setstate);
      },
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) => Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              /// 告警时间
              Container(
                margin: const EdgeInsets.only(top: 16, bottom: 6),
                child: TimeRangePicker(
                  title: ResKey.alarmTime.tr,
                  padding: EdgeInsets.only(right: 16.w),
                  startPlaceholder: ResKey.startTime.tr,
                  endPlaceholder: ResKey.stopTime.tr,
                  startTime: startTime,
                  endTime: endTime,
                  onChange: (start, end) {
                    startTime = start;
                    endTime = end;
                    reqParams.startTime =
                        '${startTime.replaceAll('/', '-')} 11:50:00';
                    reqParams.endTime =
                        '${endTime.replaceAll('/', '-')} 11:51:00';
                  },
                ),
              ),

              /// 站点
              const SizedBox(height: 3),
              Visibility(
                  visible: isTabPage != null && isTabPage!,
                  child: FilterSiteTags(
                    selectedSites: selectedSites,
                    onChange: (sites) {
                      selectedSites = sites;
                      print("一直是 $selectedSites");
                    },
                  )),

              /// 清除状态
              FilterStatusTags<dynamic>(
                isHistoryAlarm
                    ? AlarmClearStatusType.values
                    : AlarmStatusType.values,
                labelName: (status) => status.label,
                title: ResKey.clearState.tr,
                isSingleSelect: true,
                spacing: 11.w,
                tagWidth: 104.w,
                selectTags: selectTag,
                onSelect: (status) {
                  selectTag = status ?? [];
                  reqParams.recoverType = status?[0].value;
                  reqParams.status = status?[0].value;
                },
              ),
            ],
          ),
        );
      },
    );
  }
}
